package com.example.demo.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

/**
 * 二维码工具类
 *
 * @date 2016年4月6日
 */
@SuppressWarnings("unused")
public class QRCodeUtils
{

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;

    // LOGO宽度
    private static final int WIDTH = 80;
    // LOGO高度
    private static final int HEIGHT = 80;

    // 二位码颜色
    private static final int BLACK = 0x663399;
    // 二维码背景颜色
    private static final int WHITE = 0xFFCC99;

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception
    {
        Hashtable hints = new Hashtable();

        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        // 二维码纠错级别：由高到低 H、Q、M、L
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        // 二维码边界空白大小由大到小 4、3、2、1(默认为4)
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        int H = bitMatrix.getHeight();
        int W = bitMatrix.getWidth();
        int L = getFinderPatternWidth(bitMatrix) + 3;
        int[] pixels = new int[W * H];
        // 二维码角颜色，依次为左上、左下、右上
        Color redColor = new Color(182, 0, 5);
        int redColorInt = redColor.getRGB();
        Color greenColor = new Color(0, 124, 54);
        int greenColorInt = greenColor.getRGB();
        Color blueColor = new Color(0, 64, 152);
        int blueColorInt = blueColor.getRGB();
        for (int y = 0; y < H; y++)
        {
            for (int x = 0; x < W; x++)
            {
                // 颜色渐变程度,RGB(158，255，158)
                int num1 = (int) (158 - (158.0 - 30.0) / bitMatrix.getHeight() * (y + 1));
                int num2 = (int) (255 - (255.0 - 80.0) / bitMatrix.getHeight() * (y + 1));
                int num3 = (int) (158 - (158.0 - 130.0) / bitMatrix.getHeight() * (y + 1));
                Color color = new Color(num1, num2, num3);
                int colorInt = color.getRGB();
                // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                //pixels[y * W + x] = bitMatrix.get(x, y) ? colorInt : 0xffffff;
                pixels[y * W + x] = bitMatrix.get(x, y) ? 0x000000 : 0xffffff;
            }
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        image.getRaster().setDataElements(0, 0, W, H, pixels);
        if (imgPath == null || "".equals(imgPath))
        {
            return image;
        }
        // 插入图片
        QRCodeUtils.insertImage(image, imgPath, needCompress);
        return image;
    }

    private static int getFinderPatternWidth(BitMatrix matrix)
    {
        int W = matrix.getWidth();
        int H = matrix.getHeight();
        int length = 0;
        boolean flag = false;
        for (int y = 0; y < H; y++)
        {
            for (int x = 0; x < W; x++)
            {
                if (matrix.get(x, y) == true)
                {
                    flag = true;
                    length++;
                } else
                {
                    if (flag != false)
                    {
                        return x;
                    }
                }
            }
        }
        return length;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception
    {
        File file = new File(imgPath);
        if (!file.exists())
        {
            System.err.println("" + imgPath + "   该文件不存在！");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress)
        {
            // 压缩LOGO
            if (width > WIDTH)
            {
                width = WIDTH;
            }
            if (height > HEIGHT)
            {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 绘制缩小后的图
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO位置
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        /*
         * int x = QRCODE_SIZE - width - 20; int y = QRCODE_SIZE - height - 20;
         */

        graph.drawImage(src, x, y, width, height, null);

        // logo边框
        /*
         * Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
         * graph.setStroke(new BasicStroke(3f)); graph.draw(shape);
         */

        graph.dispose();
    }

    // 生成二维码文件存储
    public static boolean encode(String content, String imgPath, String destPath, String fileName, boolean needCompress) throws Exception
    {

        boolean flag = false;
        BufferedImage image;
        try
        {
            image = QRCodeUtils.createImage(content, imgPath, needCompress);
            mkdirs(destPath);
            String file = fileName + ".jpg";
            ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
            flag = true;
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return flag;
    }

    // 以流的形式直接输出不存储
    public static void encode(String content, String imgPath, HttpServletResponse response, boolean needCompress) throws Exception
    {
        BufferedImage image = QRCodeUtils.createImage(content, imgPath, needCompress);
        boolean bl = ImageIO.write(image, FORMAT_NAME, response.getOutputStream());
        System.out.println(" boolean is " + bl);
    }

    public static void mkdirs(String destPath)
    {
        File file = new File(destPath);
        // 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory())
        {
            file.mkdirs();
        }
    }
}